const app = getApp();
Page({
  data: {
    allAssets: [
  
    ],
    displayAssets: [],
    searchKeyword: '',
    showMessage: false,
    message: ''
  },
  onLoad() {
 
    this.fetchAssets();
  },
   // 调用API获取资产数据
   fetchAssets() {
// 页面加载时调用接口获取数据
wx.request({
  url: `${app.globalData.api}/wx/myAssets?id=`+wx.getStorageSync('id'), // 替换为实际接口URL`${app.globalData.api}/wx/myAssets?id=`+wx.getStorageSync('id')
  success: (res) => {
    console.log(res.data.data)
    this.setData({
      displayAssets: res.data.data || [], // 直接赋值给变量
      allAssets: res.data.data || []
    });
  },
  fail: () => {
    wx.showToast({ title: '获取数据失败', icon: 'none' });
  }
});
  },
  onSearchInput(e) {
    this.setData({
      searchKeyword: e.detail.value
    });
  },
  onSearch() {
    const keyword = this.data.searchKeyword.trim().toLowerCase();
    if (keyword === '') {
      this.setData({
        displayAssets: this.data.allAssets
      });
      return;
    }
    const filteredAssets = this.data.allAssets.filter(asset => {
      return Object.values(asset).some(value => {
        return String(value).toLowerCase().includes(keyword);
      });
    });
    if (filteredAssets.length === 0) {
      this.showMessage('当前无符合条件的资产记录');
    } else {
      this.setData({
        displayAssets: filteredAssets
      });
    }
  },
  onExport() {
    let csvContent = '资产编号,资产名称,资产类别,购置日期,使用部门,当前状态,资产价值\n';
    this.data.allAssets.forEach(asset => {
      csvContent += `${asset.id},${asset.name},${asset.category},${asset.purchaseDate},${asset.department},${asset.status},${asset.value}\n`;
    });
    const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8' });
    const reader = new FileReader();
    reader.onloadend = () => {
      const base64 = reader.result.split(',')[1];
      wx.getSetting({
        success: res => {
          if (!res.authSetting['scope.writePhotosAlbum']) {
            wx.authorize({
              scope: 'scope.writePhotosAlbum',
              success: () => {
                this.saveFile(base64);
              },
              fail: () => {
                wx.showToast({
                  title: '未授权保存文件',
                  icon: 'none'
                });
              }
            });
          } else {
            this.saveFile(base64);
          }
        }
      });
    };
    reader.readAsDataURL(blob);
  },
  saveFile(base64) {
    wx.getFileSystemManager().writeFile({
      filePath: `${wx.env.USER_DATA_PATH}/资产报表.csv`,
      data: base64,
      encoding: 'base64',
      success: () => {
        wx.saveFile({
          tempFilePath: `${wx.env.USER_DATA_PATH}/资产报表.csv`,
          success: res => {
            this.showMessage('报表导出成功');
          },
          fail: () => {
            wx.showToast({
              title: '保存文件失败',
              icon: 'none'
            });
          }
        });
      },
      fail: () => {
        wx.showToast({
          title: '写入文件失败',
          icon: 'none'
        });
      }
    });
  },
  showMessage(msg) {
    this.setData({
      showMessage: true,
      message: msg
    });
    setTimeout(() => {
      this.setData({
        showMessage: false
      });
    }, 3000);
  },  // 下拉刷新
  onPullDownRefresh() {
    this.setData({
      page: 1,
      hasMore: true,
      displayAssets: []
    });
    this.fetchAssets();
    wx.stopPullDownRefresh();
  },
  
  // 上拉加载更多
  onReachBottom() {
    this.fetchAssets();
  }
});